/**
 * @(#) CongMoneyMediator.as
 *
 * @date		2009. 02. 17.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	경조사 신청 - Mediator
 * 				경조사을 조회하고 신청하는 Presentation Logic을 관리
 */
package com.skt.common_hr.congrest.view
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.OverViewMediator;
	import com.skt.common_hr.congrest.CelebrationFacade;
	import com.skt.common_hr.congrest.events.CongGwarekeyEvent;
	import com.skt.common_hr.congrest.model.CelebrationCodeProxy;
	import com.skt.common_hr.congrest.model.CelebrationProxy;
	import com.skt.common_hr.congrest.model.CongMoneyWriteProxy;
	import com.skt.common_hr.congrest.model.SupportStandardProxy;
	import com.skt.common_hr.congrest.model.vo.CongMoneyWriteVO;
	import com.skt.common_hr.congrest.view.components.CelebrationDetailView;
	import com.skt.common_hr.congrest.view.components.CongrestOverViewNos;
	import com.wcl.utils.DateUtil;

	import flash.events.Event;

	import mx.collections.ArrayCollection;

	import org.puremvc.as3.multicore.interfaces.INotification;

	public class CelebrationMediator extends OverViewMediator
	{
		public static const NAME:String = "CelebrationMediator";


		/**
		* 생성자
		*
		* @param
		* @return void
		*/
        public function CelebrationMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
        }

		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		override protected function initializeView():void
 		{
 			loadSupportStandard();
			super.initializeView();
 		}

		override protected function activatedView():void
		{
			super.activatedView();
 			loadCelebrationList();
			setEventListener();
 			view.vsCompensation.selectedIndex = 0;
		}

		override protected function closedView():void
		{
			removeEventListener();
		}

 		private function setEventListener():void
 		{
			view.addEventListener(CongrestOverViewNos.CongMoneyWrite, onClickNew);
			view.addEventListener(CongGwarekeyEvent.SELECT_DATA, onClickReadOnly);
			view.addEventListener(CongGwarekeyEvent.UPDATE_DATA, onClickModify);
			view.addEventListener(CongGwarekeyEvent.DELETE_DATA, onClickDelete);
			view.addEventListener(CongGwarekeyEvent.PRINT_DATA, onClickPrint);
			//view.addEventListener(CongGwarekeyEvent.PRINT_DATA2, onClickPrint2);
			view.congDetailView.addEventListener(CelebrationDetailView.ClosedDetailView, onCloseDetailView);

			//view.addEventListener(CelebrationOverViewNos.SELECTED_ITEM, onSelectedPreApproval);
 		}

 		private function removeEventListener():void
 		{
			view.removeEventListener(CongrestOverViewNos.CongMoneyWrite, onClickNew);
			view.removeEventListener(CongGwarekeyEvent.SELECT_DATA, onClickReadOnly);
			view.removeEventListener(CongGwarekeyEvent.UPDATE_DATA, onClickModify);
			view.removeEventListener(CongGwarekeyEvent.DELETE_DATA, onClickDelete);
			view.removeEventListener(CongGwarekeyEvent.PRINT_DATA, onClickPrint);
			view.congDetailView.removeEventListener(CelebrationDetailView.ClosedDetailView, onCloseDetailView);
 		}

		// 20110916 품의서 조회시..
//		private function onSelectedPreApproval(e:Event):void
//		{
//			var medi:ApprovalViewMediator = facade.retrieveMediator(ApprovalViewMediator.NAME) as ApprovalViewMediator;
//			if(medi==null) {
//				medi = new ApprovalViewMediator();
//				facade.registerMediator(medi);
//			}
//			//medi.execView(view, view.selectedItem.GWAREKEY02);
//			medi.execView(view, '11111');
//		}

 		private function loadCelebrationList():void
 		{
 			var congProxy:CelebrationProxy = facade.retrieveProxy(CelebrationProxy.NAME) as CelebrationProxy;
			congProxy.loadList(Variables.myPernr);
 		}

 		private function loadSupportStandard():void
 		{
 			var proxy:SupportStandardProxy = facade.retrieveProxy(SupportStandardProxy.NAME) as SupportStandardProxy;
 			proxy.load();

 			var codeProxy:CelebrationCodeProxy = facade.retrieveProxy(CelebrationCodeProxy.NAME) as CelebrationCodeProxy;
 			var begin:Date = DateUtil.todayNoTime();
 			begin.month -= 6;
 			var end:Date = DateUtil.todayNoTime();
 			end.month += 6;
 			codeProxy.loadHolidays(begin, end);
 		}






		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		*
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array
		{
			return basicInterestMessages.concat([
					CelebrationFacade.LOAD_CELEBRATION_LIST_COMPLETE,
					CelebrationFacade.LOAD_CELEBRATION_LIST_FAILED,
					CelebrationFacade.LOAD_CONGMONEY_SAVE_COMPLETE,
					CelebrationFacade.LOAD_CONGMONEY_SAVE_FAILED,
					CelebrationFacade.LOAD_CONGMONEY_DELETE_COMPLETE,
					CelebrationFacade.LOAD_CONGMONEY_DELETE_FAILED,
					CelebrationFacade.LOAD_CELEBRATION_DETAIL_COMPLETE,
					CelebrationFacade.LOAD_CELEBRATION_DETAIL_FAILED,
					CelebrationFacade.LOAD_CONGMONEY_PRINT_COMPLETE,
					CelebrationFacade.LOAD_CONGMONEY_PRINT_FAILED,
					CelebrationFacade.LOAD_CONGMONEY_SAVEFAL_FAILED,
					CelebrationFacade.LOAD_CONGMONEY_CORSNVIEW_COMPLETE,
					CelebrationFacade.LOAD_CONGMONEY_CORSNVIEW_FAILED,
					ReqCelebrationMediator.CLOSED_REQUEST_VIEW,
					CelebrationCodeProxy.LOAD_HOLIDAYS_COMPLETE,
					CelebrationCodeProxy.LOAD_HOLIDAYS_FAILED
					]);
		}


		/**
		* Noti별로 처리한다.
		*
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			super.handleNotification(note);
			switch(note.getName())
			{
				// 리스트 조회 Proxy 호출결과 처리
				case CelebrationFacade.LOAD_CELEBRATION_LIST_COMPLETE:
					setListView(CelebrationProxy(note.getBody()).celebrationList);
					break;
				case CelebrationFacade.LOAD_CELEBRATION_LIST_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "ALERT_FAILED_LOAD_LIST", null, "ALERT_TITLE_SYSTEM_ERROR");
					break;
				case CelebrationFacade.LOAD_CONGMONEY_DELETE_COMPLETE:
					//삭제후 조회
					loadCelebrationList();
					break;
				case CelebrationFacade.LOAD_CONGMONEY_DELETE_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "ALERT_FAILED_DELETE", null, "ALERT_TITLE_SYSTEM_ERROR");
					break;
				case CelebrationFacade.LOAD_CONGMONEY_PRINT_COMPLETE:
					onPrintDataLoad(note.getBody() as CelebrationProxy);
					break;
				case CelebrationFacade.LOAD_CONGMONEY_PRINT_FAILED:
					trace("LoadCongmoneyPrintFailed");
					break;
				case CelebrationFacade.LOAD_CELEBRATION_DETAIL_COMPLETE:
					//onSelectedDataLoad( as );
					setDetailView(CelebrationProxy(note.getBody()).detailVO);
					//setStatusMessage("경조금 내역이 조회되었습니다.");
					break;
				case CelebrationFacade.LOAD_CELEBRATION_DETAIL_FAILED:
					trace("LoadCongmoneySelectLoadFailed");
					break;



				case ReqCelebrationMediator.CLOSED_REQUEST_VIEW:
					view.vsCompensation.selectedIndex = 0;
					loadCelebrationList();
					break;
				case CelebrationFacade.LOAD_CONGMONEY_SAVEFAL_FAILED:
					onSaveFailedErroryMessage(note.getBody() as CongMoneyWriteProxy);
					break;
				case CelebrationFacade.LOAD_CONGMONEY_CORSNVIEW_COMPLETE:
					onCorsnLoad(note.getBody() as CelebrationProxy);
					break;
				case CelebrationFacade.LOAD_CONGMONEY_CORSNVIEW_FAILED:
					//view.printView.doPrint();
					break;
				case CelebrationCodeProxy.LOAD_HOLIDAYS_COMPLETE:
					trace("loaded holidays");
					break;
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}


 		/**
		 * Proxy에서 DataLoad를 완료한 후 호출됨
		 *     - load된 데이터를 화면에 출력
		 * @param
		 * @return void
		 */
 		private function setListView(list:ArrayCollection):void
 		{
 			view.congMoneyDataList = list;
 			commonFacade.setStatusMessage("STATUS_LOADED_LIST", [list.length.toString()]);
 			if(list.length == 0) {
 				//view.showInitialTip();
 			}
 		}


		/**
		 * list조회가 성공했을 때 호출됨
		 *     - 조회상세보기
		 * @param
		 * @return void
		 */
 		private function setDetailView(vo:CongMoneyWriteVO):void
 		{
 			var proxy:SupportStandardProxy = facade.retrieveProxy(SupportStandardProxy.NAME) as SupportStandardProxy;
 			view.congDetailView.dataProvider = vo;
 			view.congDetailView.funeral = proxy.isFuneral(vo.CORSN);
 		}

		/**
		 * Proxy에서 DataLoad를 완료한 후 호출됨
		 *     - 프린트
		 * @param
		 * @return void
		 */
 		private function onPrintDataLoad(proxy:CelebrationProxy):void
 		{
 			//PopUpManager.addPopUp(view.printView, view);
 			//PopUpManager.centerPopUp(view.printView);
 			if(Variables.company == "SAC") {
 				view.printViewSac.vo = proxy.printDataVO;
 			}
 			else {
 				view.printView.vo = proxy.printDataVO;
 			}
 			//view.printView.doPrint();

 			//사유
 			var corsGubun:String;
 			if(proxy.printDataVO.CPERNR == Variables.myPernr) {
				corsGubun = ""; //본인인경우
			} else {
				corsGubun = "X"; //대상자병경시
			}
			var corsnProxy:CelebrationProxy = facade.retrieveProxy(CelebrationProxy.NAME) as CelebrationProxy;
			corsnProxy.corsnLoad(corsGubun);
 		}


  		//저장에러 메세지 휴가중복메세지
 		private function onSaveFailedErroryMessage(proxy:CongMoneyWriteProxy):void
 		{
 			view.vsCompensation.selectedIndex = 0;
 			CommonAlert.showMessage(commonFacade.bundle, "ALERT_FAILED_SAVE");
 		}


 		//사유(프린트)
 		private function onCorsnLoad(proxy:CelebrationProxy):void
 		{
 			var index:int;

 			if(Variables.company == "SAC") {
	 			index = findCodeIndex(view.printViewSac.vo.CORSN,proxy.congCorsn);

	 			if(index != -1) {
	 				view.printViewSac.cornm = proxy.congCorsn[index].label;
	 			}

	 			view.printViewSac.doPrint();
	 		}
	 		else {
	 			index = findCodeIndex(view.printView.vo.CORSN,proxy.congCorsn);

	 			if(index != -1) {
	 				view.printView.cornm = proxy.congCorsn[index].label;
	 			}

	 			view.printView.doPrint();
	 		}
 		}














		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Event handler (from View, Internal or....)
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////

		/**
		 * 경조사 조회버튼 이벤트
		 * @param
		 * @return void
		 */
 		private function onClickReadOnly(event:CongGwarekeyEvent):void
 		{
 			commonFacade.setStatusMessage("");
 			view.vsCompensation.selectedIndex = 2;

			var congProxy:CelebrationProxy = facade.retrieveProxy(CelebrationProxy.NAME) as CelebrationProxy;
			congProxy.loadDetail(event.key);

 		}

 		/**
		 * 경조사   신규 신청 버튼 처리
		 * @param
		 * @return void
		 */
 		private function onClickNew(event:Event):void
 		{

 			var param:Object = new Object();
 			param.pernr 	= Variables.myPernr;
 			param.name  	= Variables.myName;
 			param.gwarekey  = "";

 			executeReqView(param);
 		}


 		/**
		 * 수정 버튼 클릭시 실행
		 * @param
		 * @return void
		 */
 		private function onClickModify(event:CongGwarekeyEvent):void
 		{
			var param:Object = new Object();
 			param.gwarekey  = event.key;
 			param.pernr = event.cpernr;
 			param.name  = Variables.myName;

 			executeReqView(param);
 		}


 		/**
		 * 삭제 버튼 클릭시 실행
		 * @param
		 * @return void
		 */
 		private function onClickDelete(event:CongGwarekeyEvent):void
 		{
 			var congProxy:CelebrationProxy = facade.retrieveProxy(CelebrationProxy.NAME) as CelebrationProxy;
			congProxy.deleteData(event.key, event.wstatus);
 		}



 		/**
		 * 프린트
		 * @param
		 * @return void
		 */
 		private function onClickPrint(event:CongGwarekeyEvent):void
 		{
 			var congProxy:CelebrationProxy = facade.retrieveProxy(CelebrationProxy.NAME) as CelebrationProxy;
			congProxy.printData(event.key);
 		}


 		/**
		 * 경조사 조회닫기
		 * @param
		 * @return void
		 */
 		private function onCloseDetailView(event:Event):void
 		{
 			view.vsCompensation.selectedIndex = 0;
 			//setStatusMessage("");
 		}



 		/**
		 * 경조사 신규 신청 및 수정 화면 실행
		 * @param
		 * @return void
		 */
 		private function executeReqView(param:Object):void
 		{
 			commonFacade.setStatusMessage("");
			view.vsCompensation.selectedIndex = 1;

 			var writeMediator:ReqCelebrationMediator = facade.retrieveMediator(ReqCelebrationMediator.NAME) as ReqCelebrationMediator;

 			if(!writeMediator) {
				writeMediator = new ReqCelebrationMediator(view.congWriteView);
	 			facade.registerMediator(writeMediator);
			}
 			if(writeMediator) facade.sendNotification(CelebrationFacade.LOAD_CONGMONEY_WRITE_INITIAL, param);
 		}




		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
 		private function findCodeIndex(key:String, srcArr:ArrayCollection):int
		{
			for(var i:int=0; i<srcArr.length; i++) {
				if(srcArr[i].data == key) {
					return i;
				}
			}
			return -1;
		}

       private function get view():CongrestOverViewNos
        {
            return viewComponent as CongrestOverViewNos;
        }


	}
}